package com.xgkj.diyiketang.fragment;

import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.umeng.analytics.MobclickAgent;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.activity.LoginActivity;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.CityListActivity;
import com.xgkj.diyiketang.activity.MyMessageActivity;
import com.xgkj.diyiketang.activity.SearchActivity;
import com.xgkj.diyiketang.activity.data.ListViewAdapter;
import com.xgkj.diyiketang.data.AdvertiseInfo;
import com.xgkj.diyiketang.data.FoodInfo;
import com.xgkj.diyiketang.data.VideoInfo;
import com.xgkj.diyiketang.data.VideoParentInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.AdvertisementTask;
import com.xgkj.diyiketang.task.FoodListTask;
import com.xgkj.diyiketang.task.VideoListTask;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.weidget.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import static com.xgkj.diyiketang.activity.GuoxueVideoTwoActivity.used_minge;

/**
 * Created by Administrater on 2015/12/8.
 */
public class VideoFragment extends BaseFragment implements View.OnClickListener, PullToRefreshListView.OnRefreshListener {
    public static final String WEIDUMESSAGE_ACTION = "weidumessage";
    private Context mContext;
    //    private GridView videoList;
//    private VideoAdapter mVideoAdapter;
    private List<VideoInfo> mList = new ArrayList<VideoInfo>();
    private PullToRefreshListView mListView;
    private ListViewAdapter mListViewAdapter;
    private ArrayList<VideoParentInfo> mArrayList;
    private ImageView searchText;
    private int getVideoListTaskId = -1;
    private String count;
    private String typeName;
    private int advertiseId = -1;
    private List<AdvertiseInfo> adList = new ArrayList<AdvertiseInfo>();
    private LocationManager mLocationManager;
    public LocationClient mLocationClient;
    public MyLocationListener mMyLocationListener;
    // private LocationClientOption.LocationMode tempMode = LocationClientOption.LocationMode.Hight_Accuracy;
    private String tempcoor = "gcj02";
    private TextView local_video;
    private String localstring;
    private int getfoodlistTaskId = -1;
    private ImageView myMgsView;
    private String areaid;
    private int currentPageAll = 1;
    //private TextView unreadAddressLable;
    private WeiduReceive weiduReceiver = null;
    private String mLocalFrist;
    private String pay_success = "";


    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.videofragment, null);
        mContext = getActivity();
        //mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        mLocationClient = new LocationClient(mContext);
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);

        if(weiduReceiver==null){
            weiduReceiver = new WeiduReceive();
            IntentFilter messageFilter = new IntentFilter(VideoFragment.WEIDUMESSAGE_ACTION);
            mContext.registerReceiver(weiduReceiver,messageFilter);
        }
        initView(view);
        return view;
    }

    private void initView(View view) {
        if (!TextUtils.isEmpty(EatShowApp.getACache().getAsString("pay_success")))
            pay_success = EatShowApp.getACache().getAsString("pay_success");
        myMgsView = (ImageView) view.findViewById(R.id.mymessage);
        myMgsView.setOnClickListener(this);
        // unreadAddressLable = (TextView) view.findViewById(R.id.unread_address_number);

//        int count = getUnreadMsgCountTotal();
//        PalLog.e("@@@@@@@@@@@消息未读数:", count + "");
        local_video = (TextView) view.findViewById(R.id.local_video);
        local_video.setOnClickListener(this);
        searchText = (ImageView) view.findViewById(R.id.search);
        searchText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, SearchActivity.class));
            }
        });
        //initData();
        mListView = (PullToRefreshListView) view.findViewById(R.id.listView);
        mListView.init(mContext, true);
        mListViewAdapter = new ListViewAdapter(mContext);
        mListView.setAdapter(mListViewAdapter, true);
        mListView.setOnRefreshListener(this);
        // mListView.setOnLoadDataListener(this);
        mListView.doRefresh();
        // mListView.disableFootview();
        getLocation();
        //getAdList();
        // getViewList();

        //local_video.setText(localstring);
    }

    private void getLocation() {
        PalLog.e("TAG", "定位中");
        initBaiduLocation();
        mLocationClient.start();
    }

    private void initBaiduLocation() {
        LocationClientOption option = new LocationClientOption();
        //option.setLocationMode(tempMode);//设置定位模式
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType(tempcoor);//返回的定位结果是百度经纬度，默认值gcj02
        //option.setScanSpan(10000);//设置发起定位请求的间隔时间为5000ms
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(weiduReceiver!=null){
            mContext.unregisterReceiver(weiduReceiver);
            weiduReceiver = null;
        }
    }

    private void getAdList() {
//        if (advertiseId != -1) {
//            return;
//        }
        if (currentPageAll == 0) {
            mListView.setNoNextPage();
            return;
        }

        AdvertisementTask adtask = new AdvertisementTask("2", "7");
        adtask.addListener(new VideoListListner(mContext));
        advertiseId = getEatShowApp().getTaskManager().addTask(adtask);
    }

    private void  getViewList() {
        VideoListTask task = new VideoListTask(null,"1");
        task.addListener(new VideoListListner(mContext));
        getVideoListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void getfoodList() {
        // PalLog.e("11111111111111",localstring);

        FoodListTask ftask = new FoodListTask(10, 1, localstring);
        ftask.addListener(new VideoListListner(mContext));
        getfoodlistTaskId = getEatShowApp().getTaskManager().addTask(ftask);
    }

//    @Override
//    public void onPullRefresh() {
//
//    }
//
//    @Override
//    public void onLoadMore() {
//       // getAdList();
//    }

    @Override
    public void onRefresh() {
        currentPageAll = 1;
        getAdList();
    }

    class VideoListListner extends ShowToastTaskEventListener {

        public VideoListListner(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == getVideoListTaskId) {
                mListViewAdapter.clearData();
                mListView.onRefreshComplete();

                if (data != null) {
                    List<VideoParentInfo> pinfoList = (List<VideoParentInfo>) data;
                    if (pinfoList != null && pinfoList.size() > 0) {
                        mListViewAdapter.updateData(pinfoList);
                    }


                }
            } else if (taskId == advertiseId) {
                advertiseId = -1;
//                if (currentPageAll == 1) {
//
//                    mListView.enableLoadMore();
//                } else {
//                    mListView.onLoadDataComplete(true);
//                }

                if (data != null) {
                    adList = (List<AdvertiseInfo>) data;
                    mListViewAdapter.addImageView(adList);
                    getfoodList();

                }


                // currentPageAll = result;
                PalLog.e("dangqiang", currentPageAll + "");
            } else if (taskId == getfoodlistTaskId) {
                if (data != null) {
//                    List<FoodInfo> finfolist = (List<FoodInfo>) data;
//                    PalLog.e("@@@@@@@@@",finfolist.size()+"");
                    List<FoodInfo> mfoodlist = new ArrayList<FoodInfo>();
                    int pageCount = 0;
                    int currentPage = 0;
                    int nextPage = 0;

                    JSONObject jsonString = (JSONObject) data;
                    currentPage = jsonString.getIntValue(ProtocolConst.CURRENT_PAGE);
                    pageCount = jsonString.getIntValue(ProtocolConst.PAGE_COUNT);
                    nextPage = currentPage >= pageCount ? 0 : (currentPage + 1);
                    areaid = jsonString.getString("areaId");
                    mListViewAdapter.setAreaId(areaid);
                    mfoodlist = JSON.parseArray(jsonString.getString(ProtocolConst.LIST_TAG), FoodInfo.class);
                    mListViewAdapter.addFoodList(mfoodlist);
                    getViewList();
                }

            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            mListView.onRefreshComplete();
            if (taskId == advertiseId) {
                advertiseId = -1;
                getfoodList();
            }else if (taskId == getfoodlistTaskId){
                getViewList();
            }
        }
    }

    private void initData() {
        mArrayList = new ArrayList<VideoParentInfo>();
        for (int i = 0; i < 10; i++) {
            VideoParentInfo pInfo = new VideoParentInfo();
            pInfo.setTypeName("第i个");
            List<VideoInfo> vList = new ArrayList<VideoInfo>();
            for (int j = 0; j < 4; j++) {
                VideoInfo info = new VideoInfo();
                info.setVideoTitle("aaa");
                info.setVideoIntroduction("dafadfasf");
                info.setVideoDuration("12:00");
                info.setVideoLogo("http://pic.nipic.com/2007-11-09/2007119122519868_2.jpg");
                vList.add(info);
            }
            pInfo.setList(vList);
            mArrayList.add(pInfo);
        }
    }

    //    private void initView(View view){
//        videoList = (GridView) view.findViewById(R.id.video_list);
//        mVideoAdapter = new VideoAdapter(mContext);
//        //mVideoAdapter.updateData(mList);
////        videoList.setOnItemClickListener(goodsItemClickListener);
//        videoList.setAdapter(mVideoAdapter);
//
//             //  mVideoAdapter.updateData(mList);
//    }
    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.mymessage:
                //getFragmentManager().beginTransaction().replace(R.id.content, new MessageFragment()).commit();
//                Intent intent = new Intent(mContext, MyMessageActivity.class);
//                startActivity(intent);
                if(getEatShowApp().getmUserInfo()!= null) {
                    Intent intent = new Intent(mContext, MyMessageActivity.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.local_video:
                Intent cintent = new Intent(mContext, CityListActivity.class);
                startActivityForResult(cintent, 1);
                break;
            default:
                break;
        }

    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            sb.append("\ncity : ");
            sb.append(location.getCity());

            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");
//                localstring = location.getCity();
//                mListViewAdapter.setAreaName(localstring);
//                EatShowSetting.getInstance(mContext).setLocal(localstring);
                localstring = location.getCity();
                mLocalFrist = location.getCity();
                mListViewAdapter.setAreaName(localstring);
                EatShowSetting.getInstance(mContext).setLocal(localstring);
                EatShowSetting.getInstance(mContext).setFirstLocal(mLocalFrist);


            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                local_video.setText(location.getCity());
//                localstring = location.getCity();
//                EatShowSetting.getInstance(mContext).setLocal(localstring);
//                mListViewAdapter.setAreaName(localstring);
                localstring = location.getCity();
                mLocalFrist = location.getCity();
                mListViewAdapter.setAreaName(localstring);
                EatShowSetting.getInstance(mContext).setLocal(localstring);
                EatShowSetting.getInstance(mContext).setFirstLocal(mLocalFrist);

                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {

                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            PalLog.e("BaiduLocationApiDem", sb.toString());
            if (location != null) {
                mLocationClient.stop();
                PalLog.e("定位完成", "百度定位完成");

            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {

//            mListViewAdapter.clearData();
//            getAdList();
            updateUnreadAddressLable();
            if (mListViewAdapter != null && mListViewAdapter.getCount() == 0) {
                mListView.doRefresh();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(pay_success)){
            if (pay_success.equals("true")){
                pay_success="";
                getViewList();
            }
        }
        if (used_minge){
            getViewList();
        }
        MobclickAgent.onPageStart("VideoFragment");
        updateUnreadAddressLable();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("VideoFragment");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // String
        if (data != null) {
            //areaid = data.getExtras().getString("areaId");
            // mListViewAdapter.setAreaId(areaid);

//            localstring = data.getExtras().getString("areaName");
//            mListViewAdapter.setAreaName(localstring);
//            PalLog.e("fdsafdsaf", localstring);
//            local_video.setText(localstring);
//            mListViewAdapter.clearData();
//            getfoodList();

            localstring = data.getExtras().getString("areaName");
            EatShowSetting.getInstance(mContext).setLocal(localstring);
            mListViewAdapter.setAreaName(localstring);
            local_video.setText(localstring);
            mListViewAdapter.clearData();
            getfoodList();
        }


    }

    private int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    /**
     * 刷新申请与通知消息数
     */
    private void updateUnreadAddressLable() {
//        int count = getUnreadMsgCountTotal();
//        PalLog.e("@@@@@@@@@@@消息未读数:", count + "");
//                if (count > 0) {
//
//                    unreadAddressLable.setVisibility(View.VISIBLE);
//                } else {
//                    unreadAddressLable.setVisibility(View.INVISIBLE);
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadMsgCountTotal();
                if (count > 0) {
//					unreadAddressLable.setText(String.valueOf(count));
                    // unreadAddressLable.setVisibility(View.VISIBLE);
                    myMgsView.setBackgroundResource(R.drawable.youxiaoxi);

                } else {
                    // unreadAddressLable.setVisibility(View.INVISIBLE);
                    myMgsView.setBackgroundResource(R.drawable.message_logo);
                }

            }
        });
//                }
    }

    public void refresh() {
        updateUnreadAddressLable();
    }

    public class WeiduReceive extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            refresh();
        }
    }


}
